// 菜单管理控制器
const Role = require('../models/role.model');
const Menu = require('../models/menu.model');
const sendResponse = require('../utils/response');
const dateFormatter = require('../utils/dateFormatter');
const buildMenuTree = require('../utils/menuTree');

// 获取所有菜单
exports.getAllMenu = async (req, res, next) => {
  try {
    // const menuList = await Menu.findAll();
    const menuList = await buildMenuTree([]);
    // 使用改进后的 dateFormatList 函数格式化日期字段
    const formattedMenu = dateFormatter.dateFormatList(menuList, ['createTime', 'updateTime']);

    return sendResponse(res, { message: '获取菜单成功', data: formattedMenu });
  } catch (error) {
    next(error);
  }
};

// 添加菜单
exports.createMenu = async (req, res, next) => {
  try {
    const {  name, level, code, pid } = req.body;
    console.log(level);
    // 判断菜单是否存在
    const hasCode = await Menu.findOne({ where: { code } });
    if (hasCode) {
      return sendResponse(res, { code: 400, message: '菜单已存在' });
    }
    // 验证数据
    if (!pid || !name || !code || !level) {
      return sendResponse(res, { code: 400, message: '缺少必填字段' });
    }
    // 创建菜单
    const menu = await Menu.create({ pid, name, code, status: 1, level  });
    console.log("----添加菜单成功----");

    return sendResponse(res, { message: '添加菜单成功', data: menu });
  } catch (error) {
    next(error);
  }
};

// 更新菜单
exports.updateMenu = async (req, res, next) => {
  const { id, name, level, code, pid } = req.body;
  try {
    // 判断菜单是否存在
    const hasCode = await Menu.findOne({ where: { code } });
    if (hasCode && hasCode.id !== id) {
      return sendResponse(res, { code: 400, message: '菜单已存在' });
    }
    
    await Menu.update({ name, level, code, pid }, { where: { id } });
    console.log("----更新菜单----");
    return sendResponse(res, { message: '更新菜单成功' });
  } catch (error) {
    next(error);
  }
};

// 删除菜单
exports.removeMenu = async (req, res, next) => {
  const { id } = req.params;
  try {
    // 判断菜单是否存在
    const menu = await Menu.findByPk(id);
    if (!menu) {
      console.log("----菜单不存在----");
      return sendResponse(res, { code: 404, message: '菜单不存在' });
    }

    // 判断菜单下是否有子菜单
    const hasChild = await Menu.findOne({ where: { pid: id } });
    if (hasChild) {
      console.log("----菜单下存在子菜单，无法删除----");
      return sendResponse(res, { code: 400, message: '菜单下存在子菜单，无法删除' });
    }

    // 删除菜单
    await Menu.destroy({ where: { id } });
    console.log("----删除菜单----");
    
    return sendResponse(res, { message: '删除菜单成功' });
  } catch (error) {
    next(error);
  }
};

// 获取某一个角色菜单列表和全部菜单树
exports.toAssign = async (req, res, next) => {
  try{
    const roleId = parseInt(req.params.roleId);
    // 检查角色是否存在
    const existingRole = await Role.findByPk(roleId);
    if (!existingRole) {
      console.log("---角色id不存在---");
      return sendResponse(res, { code: 404, message: '角色id不存在！' });
    }
    // 获取角色的菜单列表
    const roleMenus = await existingRole.getMenus();
    // 获取所有菜单权限包括菜单树
    const MenuTree = await buildMenuTree(roleMenus)
    return sendResponse(res, { message: '获取角色菜单列表成功', data: MenuTree });
  } catch (error) {
    next(error);
  }
}

// 给角色分配权限
exports.doAssign = async (req, res, next) => {
  // console.log(req);
  try {
    const { roleId, permissionId } = req.query;
    const roleIds = permissionId.split(','); // 权限 ID
    console.log(roleId, roleIds);

    // 获取角色
    const role = await Role.findByPk(roleId);

    if (!role) {
      return sendResponse(res, { code: 404, message: '角色不存在' });
    }

    // 分配权限
    await role.setMenus(roleIds);

    // 返回成功响应
    return sendResponse(res, { message: '分配权限成功' });
  } catch (error) {
    next(error);
  }
};